import { Response } from 'express'
import { v4 as uuid } from 'uuid'
import {commonResponse} from "../utils/commonResponse";
import {IPromiseCommonResponse, ISqlInsert, tokenParams} from "../../global";
import {parseToken} from "../utils/jwt";
import {
    addRecentlyDao,
    delRecentlyDao,
    editRecentlyDao,
    IRecently,
    recentlyListDao,
    recentlyViewDao
} from "../dao/recentlyDao";
import dayjs from "dayjs";
import FileMethod from "../utils/fileMethod";

export const recentlyListService = async (res: Response, token: string, name: string) => {
    await commonResponse<IPromiseCommonResponse<Array<IRecently>>, Array<IRecently>>(res, async () => {
        const params = parseToken(token) as tokenParams
        const list = await recentlyListDao([params.userUID, `%${name}%`])
        for (let i = 0; i < list.length; i++) {
            list[i].key = list[i].recentlyUID
        }
        return Promise.resolve({ code: 200, data: list })
    })
}

export const addRecentlyService = async (res: Response, token: string, name: string, describe: string, path: string) => {
    await commonResponse<IPromiseCommonResponse<ISqlInsert>, ISqlInsert>(res, async () => {
        const params = parseToken(token) as tokenParams
        const data = await addRecentlyDao([uuid(), params.userUID, path, name, describe, dayjs().format('YYYY-MM-DD HH:mm:ss')])
        return Promise.resolve({  code: 200, data })
    })
}

export const delRecentlyService = async (res: Response, list: Array<string>) => {
    await commonResponse<IPromiseCommonResponse<ISqlInsert>, ISqlInsert>(res, async () => {
        return Promise.resolve({ code: 200, data: await delRecentlyDao([list])})
    })
}

export const recentlyViewService = async (res: Response, path: string) => {
    await commonResponse<IPromiseCommonResponse<Array<IRecently>>, Array<IRecently>>(res,  async () => {
        return Promise.resolve({ code: 200, data: await recentlyViewDao([path])})
    })
}

export const recentlyEditService = async (res: Response, name: string, describe: string, path: string) => {
    await commonResponse<IPromiseCommonResponse<ISqlInsert>, ISqlInsert>(res, async () => {
        return Promise.resolve({ code: 200, data: await editRecentlyDao([name, describe, path])})
    })
}